﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Sunlight.Manage.BusinessInterface.IService;
using Sunlight.Manage.Common.Result;
using Sunlight.Manage.Common.utils;
using Sunlight.Manage.MentApi.Utility.Filters;
using Sunlight.Manage.MentApi.Utility.SwaggerExt;
using Sunlight.Manage.Model.Domain.DTO;
using Sunlight.Manage.Model.Entity;

namespace Sunlight.Manage.MentApi.Controllers.SystemApi
{
    /// <summary>
    /// User
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [CustomAsyncExceptionFilter]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersion.V1))]
    public class UserController : ControllerBase
    {

        /// <summary>
        /// 用户信息的分页查询
        /// </summary>
        /// <param name="userManagerService"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetUserPage([FromServices] UserManagerService userManagerService, [FromServices] IMapper mapper, int pageIndex,int pageSize,string? searchaString=null) {

            Expressionable<Sys_User> expressionable = new Expressionable<Sys_User>();
            expressionable.AndIF(!string.IsNullOrWhiteSpace(searchaString), u => u.Name.Contains(searchaString));

            PagingData<Sys_User> paging = userManagerService.QueryPage<Sys_User>(expressionable.ToExpression(), pageSize, pageIndex, c => c.UserId, false);

            ApiDataResult<PagingData<SysUserDTO>> result = new ApiDataResult<PagingData<SysUserDTO>>()
            {
                Data = mapper.Map<PagingData<Sys_User>, PagingData<SysUserDTO>>(paging),
                Success = true,
                Message = "用户分页查询"
            };

            return await Task.FromResult(new JsonResult(result));
        }

        /// <summary>
        /// 【添加用户】
        /// </summary>
        /// <param name="userManagerService"></param>
        /// <param name="mapper"></param>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomAsyncValidateParaActionFilter]
        public async Task<JsonResult> AddUser([FromServices] UserManagerService userManagerService, [FromServices]IMapper mapper,SysUserDTO userDTO) {
            Sys_User addUser = mapper.Map<SysUserDTO, Sys_User>(userDTO);
            userManagerService.Insert(addUser);
            var result = new JsonResult(
                new ApiDataResult<Sys_User>() 
                { 
                    Data = addUser,
                    Success = true, 
                    Message = "添加用户" 
                }
            );
            return await Task.FromResult(result);
        }

    }
}
